import { readOnly, parsePath } from "./utils";

let location = getLocation()
// 获取当前页面的location对象
function getLocation() {
  const { pathname, hash, search } = window.location;
  return readOnly({
    pathname,
    search,
    hash,
    state: null,
  });
}

// 获取下一个页面的location对象
function getNextLocation(to, state) {
  return readOnly({
    ...parsePath(to),
    state,
  })
}

// 监听path变化
let listeners = []
function listen(fn) {
  listeners.push(fn)

  return function() {
    // 取消订阅
    listeners = listeners.filter(listener => listener !== fn)
  }
}

// 调用history.pushState方法，改变url
function push(to, state) {
  location = getNextLocation(to, state)
  window.history.pushState(state, "", to);
  listeners.forEach(fn => fn(location))
}

// 处理浏览器的前进和后退操作
window.addEventListener('popstate', () => {
  location = getLocation()
  listeners.forEach(fn => fn(location))
})

export default {
  push,
  listen,
  get location() {
    return location
  }
};
